package com.example.administrator.text;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.greenrobot.eventbus.EventBus;
import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import data.SharedPreferencesUtils;
import util.AndroidJSInterface;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.NetUtils;
import util.NetWorkstateUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.getInformation;
import util.payUtil.PayUtil;

/**
 * WebView页  13662286198
 */
public class WebViewActivity extends BaseActivity {
    public static String mAction = "PayResult";
    private String mTitle,mToken,mId,mUrl;
    private AudioManager mAudioManager;
    private boolean mReceiverTag = false;   //广播接受者标识
    private int mNewProgress = 0;

    @Bind(R.id.wv_webview)   WebView mWebView;
    @Bind(R.id.text_webview) TextView mTVTitle; //标题
    @Bind(R.id.frame_wxpay)  FrameLayout mFrameLayout;
    @Bind(R.id.seekBar_web)  ProgressBar mProgressBar;
    @Bind(R.id.iv_webview)   ImageView mIV;
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        ButterKnife.bind(this);
        HomeUtil.getHemeUtilNew().getStatusBar(this,mFrameLayout);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        judgeWhetherNetworking();

    }

    /**
     * 判断是否给放行网络
     */
    private void judgeWhetherNetworking() {
        mTitle = getIntent().getStringExtra("title");
        mUrl = getIntent().getStringExtra("url");
        mId = (String) SharedPreferencesUtils.getParam(WebViewActivity.this, HomeUtil.mUseridDB, "");
        mToken = (String) SharedPreferencesUtils.getParam(WebViewActivity.this, HomeUtil.mTokenDB, "");
        LogUtil.eE("url","....mUrl..."+mUrl);
        if(mTitle.equals("会员购买") || mTitle.equals("套餐购买")){
            if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
                init(mUrl);
            }else {
                if(StringUtil.getStringUtilNew().judgeUIType(MyApplication.getApp().getmPattern()) == 0){
                    Toast.makeText(this,"Pattern:0 该环境不支持本功能",Toast.LENGTH_SHORT).show();
                }else {
                    String apMac = getInformation.getNewGetInformation(WebViewActivity.this).getWiFiMac();
                    if(StringUtil.getStringUtilNew().judgeMac(apMac)){
                        domain(0);
                    }else {
                        Toast.makeText(this,"apMac异常",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }else {
            init(mUrl);
        }
    }

    /**
     * 返回
     */
    @OnClick(R.id.image_webview)
    void returnWebView(){
        if(mWebView.canGoBack()){
            mWebView.goBack();
        }else {
            mWebView.onPause();
            finish();
            if(mTitle.equals("会员购买") || mTitle.equals("余额充值") || mTitle.equals("报障") || mTitle.equals("套餐购买") || mTitle.equals("套餐")){
                LogUtil.eE("domain",".......NETWORKING_ATATE............"+Url.getUrlNew().getNETWORKING_ATATE());
                if(Url.getUrlNew().getNETWORKING_ATATE() == 1){
                    NetWorkstateUtil.getInstance().getBrokenNetwork(this,null,1);
                    Url.getUrlNew().setIsonResumeJudge(false);
                    HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Url.getUrlNew().setIsonResumeJudge(true);
                        }
                    },1500);
                }
                EventBus.getDefault().post("vip");
                HomeUtil.getHemeUtilNew().saveCombo(this,0,null);
            }
        }
    }

    /**
     * 超时的点击
     */
    @OnClick(R.id.iv_webview)
    void im(){
        mIV.setVisibility(View.GONE);
        mWebView.setVisibility(View.VISIBLE);
        mWebView.loadUrl(mUrl);
        mProgressBar.setVisibility(View.VISIBLE);
        mNewProgress = 0;
        overtimeView();
    }

    @Override protected void onPause() {
        super.onPause();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
            mWebView.onPause();
        }
    }

    @Override protected void onResume() {
        if(mTVTitle.equals("支付")){
            if(getRequestedOrientation()!= ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        }

        super.onResume();
    }

    /**初始化WebView*/
    @SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
    @JavascriptInterface
    private void init(String url){

        SharedPreferencesUtils.setParam(this, PayUtil.PAY_COMMODITY,mTitle);
        mTVTitle.setText(mTitle);
        //WebView加载web资源http://
        mWebView.loadUrl(url);
        Log.e("mWebView", "                 " + url);
        //mWebView.getSettings().setDomStorageEnabled(true);                      //开启内存缓存 就可以加载1号店的图片
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);  //支持通过JS打开新窗口
        mWebView.getSettings().setLoadWithOverviewMode(true);                 // 缩放至屏幕的大小
        mWebView.getSettings().setLoadsImagesAutomatically(true);            //支持自动加载图片
        if(!mTitle.equals(getString(R.string.statement_web)) && !mTitle.equals("用户协议")){
            LogUtil.eE("","...mWebView...setUseWideViewPort..WIFL");
            mWebView.getSettings().setUseWideViewPort(true);              //webview设置自适应任意大小的pc网页
        }
        mWebView.getSettings().setBuiltInZoomControls(true);           //启用内置缩放装置
        mWebView.getSettings().setDisplayZoomControls(false);         //隐藏webview缩放按钮
        mWebView.getSettings().setJavaScriptEnabled(true);           //设置WebView属性，能够执行Javascript脚本
        AndroidJSInterface ajsi = new AndroidJSInterface(this);
        mWebView.addJavascriptInterface(ajsi,ajsi.getInterface());            //
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        mWebView.setWebViewClient(new WebViewClient() {
            @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
               /* Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                */
                LogUtil.eE("WebView","setOnClickListener"+url);
                LogUtil.eE("WebView",".....title....."+view.getTitle());
                mWebView.loadUrl(url);
                return true;
            }

            //UserInfo  mId  vip ID  模式
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view,url);
                int vip = (int) SharedPreferencesUtils.getParam(WebViewActivity.this, HomeUtil.mVIPCombonum,1);
                int pledge = (int) SharedPreferencesUtils.getParam(WebViewActivity.this, HomeUtil.mPledge,1);
                String expire_time = (String)SharedPreferencesUtils.getParam(WebViewActivity.this,HomeUtil.getHemeUtilNew().mPackage_Expire_time,"");
                if(mTitle.equals("会员购买") || mTitle.equals("余额充值") || mTitle.equals("套餐购买") || mTitle.equals("套餐")|| mTitle.equals("会员")){
                     //String string = "javascript:calljsUserInfo(" +"'"+ mId +"',"+"'"+vip+"'"+ ","+"'"+MyApplication.getApp().getmPattern()+"',"+"'"+pledge+"',"+"'"+expire_time+"'"+")";
                     String string = "javascript:calljsUserInfo(" +"'"+ mId +"',"+"'"+vip+"'"+ ","+"'"+MyApplication.getApp().getmPattern()+"',"+"'"+pledge+"',"+"'"+expire_time+"',"+"'"+MyApplication.getApp().getSiteAreaid()+"'"+")";
                     getLogger().info("getJudgeIP--->onSuccess--->"+"String--"+string);
                     mWebView.loadUrl(string);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();// 接受所有网站的证书
                // super.onReceivedSslError(view, handler, error);
                // 断网或者网络连接超时
                LogUtil.eE("Url","........error.........."+error);
            }

        });

        //进度条
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override public void onProgressChanged(WebView view, int newProgress) {
                mNewProgress = newProgress;
                if(newProgress == 100){
                    mProgressBar.setVisibility(View.GONE);
                }else {
                    mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                LogUtil.eE("WebView","onReceivedTitle..."+title);
                if(title.equals("购买套餐")){
                  domain(1);
                }
            }

        });

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(mAction);
        mReceiverTag = true;
        registerReceiver(broadcastReceiver,intentFilter);
        overtimeView();

    }
    @Override public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(mAudioManager == null){mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);}
        switch (keyCode){
            case  KeyEvent.KEYCODE_VOLUME_DOWN:
                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER,
                        AudioManager.FX_FOCUS_NAVIGATION_UP);//音量-
                break;
            case KeyEvent.KEYCODE_VOLUME_UP:
                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE,
                        AudioManager.FX_FOCUS_NAVIGATION_UP);//音量+
                break;
            case KeyEvent.KEYCODE_BACK:
                    if(mTitle.equals("会员购买") || mTitle.equals("余额充值") || mTitle.equals("报障") || mTitle.equals("套餐购买")|| mTitle.equals("套餐")){
                        LogUtil.eE("domain",".......NETWORKING_ATATE............"+Url.getUrlNew().getNETWORKING_ATATE());
                        if(Url.getUrlNew().getNETWORKING_ATATE() == 1){
                            NetWorkstateUtil.getInstance().getBrokenNetwork(this,null,1);
                            Url.getUrlNew().setIsonResumeJudge(false);
                            HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Url.getUrlNew().setIsonResumeJudge(true);
                                }
                            },1500);
                        }
                        HomeUtil.getHemeUtilNew().saveCombo(this,0,null);
                        EventBus.getDefault().post("vip");
                        mWebView.loadUrl("about:blank");
                        mWebView.onPause();
                        finish();
                    }else {
                        if(mWebView.canGoBack()){
                            mWebView.goBack();
                        }else {
                            mWebView.onPause();
                            finish();
                        }
                    }
                break;
        }
        return true;
    }

    /**
     * 当横竖屏切换时会调用该方法
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
            mFrameLayout.setVisibility(View.GONE);

        }else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            mFrameLayout.setVisibility(View.VISIBLE);
        }
    }

   /**
     *创建一个动态广播
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override public void onReceive(Context context, Intent intent) {
            String string = intent.getStringExtra("pay");
            if(!string.equals("") && string.equals("WXPAY")){
                 finish();
            }
            LogUtil.eE("string","WebViewActivity"+string);
        }
    };


    @Override protected void onDestroy() {
        super.onDestroy();
        if(broadcastReceiver !=null){
            if(mReceiverTag){
                mReceiverTag = false;
                unregisterReceiver(broadcastReceiver);
            }

        }
    }

    /**
     * 先域名访问
     * 0 一开始进来
     * 1 代码从找代理那
     */
    private void domain(final int type) {

        getLogger().info("domain()--->"+"fwq--http://123.207.110.98:8080/wifi/ping.html");
        GreenTreeNetworkUtil.getInstance().doPost(this,"http://123.207.110.98:8080/wifi/ping.html",2000,null,new RequestDataCallback() {
            @Override public void onSuccess(String response){
                getLogger().info("domain()--->response.."+response);
                if(type == 0){
                    domain1(response);
                }else if(type == 1){
                    domain2(response);
                }
            }

            @Override
            public void onFailure(Throwable error) {
                getLogger().info("domain()--->error..");
                if(type == 0){
                    domain1("fdfdf");
                }else if(type == 1){
                    domain1("fdfdf");
                }
            }
        });
    }

    private void domain1(String stirng){
        int length = stirng.length();
        LogUtil.eE("domain","......length......"+length);
        if(length == 2 || length == 1){
            Url.getUrlNew().setNETWORKING_ATATE(0);
            init(mUrl);
        }else {
            init("");
            NetWorkstateUtil.getInstance().showNetworking(WebViewActivity.this, new NetWorkstateUtil.NetworkingOnClickListener() {
                @Override
                public void onItemClick(boolean state) {
                    if(state){
                        Url.getUrlNew().setNETWORKING_ATATE(1);
                        mWebView.loadUrl(mUrl);
                    }else {
                        Url.getUrlNew().setNETWORKING_ATATE(0);
                        Toast.makeText(WebViewActivity.this, "连接网络失败，可以打开移动网络", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    private void domain2(String stirng){
        int length = stirng.length();
        LogUtil.eE("domain","......length......"+length+"..state.."+Url.getUrlNew().getNotifation_state());
        if(length >2 ){
            NetWorkstateUtil.getInstance().showNetworking(WebViewActivity.this, new NetWorkstateUtil.NetworkingOnClickListener() {
                @Override
                public void onItemClick(boolean state) {
                    if(state){
                        Url.getUrlNew().setNETWORKING_ATATE(1);
                        SharedPreferencesUtils.setParam(WebViewActivity.this, PayUtil.PAY_COMMODITY,"套餐购买");
                    }else {
                        Url.getUrlNew().setNETWORKING_ATATE(0);
                        Toast.makeText(WebViewActivity.this, "连接网络失败，可以打开移动网络", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    private void overtimeView(){
        HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(mNewProgress != 100){
                    Toast.makeText(WebViewActivity.this,"请求超时",Toast.LENGTH_SHORT).show();
                    mIV.setVisibility(View.VISIBLE);
                    mWebView.setVisibility(View.GONE);
                    mProgressBar.setVisibility(View.GONE);
                }
            }
        },15000);
    }
}
